package com.cma.cmabackend.service;

import com.cma.cmabackend.dao.EquipmentDeptDAO;
import com.cma.cmabackend.dao.LabAdminDAO;
import com.cma.cmabackend.dao.LabEmpDao;
import com.cma.cmabackend.dao.QualityDeptDAO;
import com.cma.cmabackend.entity.EquipmentDept;
import com.cma.cmabackend.entity.LabAdmin;
import com.cma.cmabackend.entity.LabEmp;
import com.cma.cmabackend.entity.QualityDept;
import com.cma.cmabackend.entity.re.ReUser;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginService {
    @Resource
    LabAdminDAO labAdminDAO;
    @Resource
    LabEmpDao labEmpDao;
    @Resource
    EquipmentDeptDAO equipmentDeptDAO;
    @Resource
    QualityDeptDAO qualityDeptDAO;

    public Map<String, Object> validate(String username, String pwd) {
        Map<String, Object> result = new HashMap<>();
        LabAdmin labAdmin = labAdminDAO.findByUsername(username);
        if (labAdmin != null) {
            if (!labAdmin.getPwd().equals(pwd)) {
                result.put("success", false);
            } else {
                result.put("success", true);
                result.put("user", new ReUser(labAdmin.getId(), labAdmin.getType(), labAdmin.getUsername()));
            }
            return result;
        }
        LabEmp labEmp = labEmpDao.findByUsername(username);
        if (labEmp != null) {
            if (!labEmp.getPwd().equals(pwd)) {
                result.put("success", false);
            } else {
                result.put("success", true);
                result.put("user", new ReUser(labEmp.getId(), labEmp.getType(), labEmp.getUsername()));
            }
            return result;
        }
        EquipmentDept equipmentDept = equipmentDeptDAO.findByUsername(username);
        if (equipmentDept != null) {
            if (!equipmentDept.getPwd().equals(pwd)) {
                result.put("success", false);
            } else {
                result.put("success", true);
                result.put("user", new ReUser(equipmentDept.getId(), equipmentDept.getType(), equipmentDept.getUsername()));
            }
            return result;
        }
        QualityDept qualityDept = qualityDeptDAO.findByUsername(username);
        if (qualityDept != null) {
            if (!qualityDept.getPwd().equals(pwd)) {
                result.put("success", false);
            } else {
                result.put("success", true);
                result.put("user", new ReUser(qualityDept.getId(), qualityDept.getType(), qualityDept.getUsername()));
            }
            return result;
        }
        result.put("success", false);
        return result;
    }
}
